package downloader

import (
	"gitee.com/Luna-CY/hui-hui/internal/toolbox/downloader"
	"gitee.com/Luna-CY/hui-hui/server/http/response"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

type StartRequest struct {
	Url     string `json:"url" validate:"required" binding:"required,url"`                                        // 下载链接
	Target  int    `json:"target" validate:"required" enums:"1,2" binding:"required,oneof=1 2"`                   // 保存目标
	Path    string `json:"path" validate:"optional" binding:"omitempty"`                                          // 资源管理器路径
	Timeout int    `json:"timeout" validate:"optional" minimum:"1" maximum:"30" binding:"omitempty,min=1,max=30"` // 有效期，单位天
}

type StartResponse struct {
	Id        string `json:"id" validate:"required"`         // 任务ID
	StartTime int64  `json:"start_time" validate:"required"` // 开始时间
	Filename  string `json:"filename" validate:"required"`   // 文件名称
	FileSize  int64  `json:"file_size" validate:"required"`  // 文件大小，单位字节
}

func (cls *Downloader) Start(c *gin.Context) (int, any, error) {
	var body = StartRequest{Target: 1, Timeout: 1}
	if err := c.ShouldBindJSON(&body); nil != err {
		return response.InvalidRequest, nil, err
	}

	var task, err = cls.downloader.Start(body.Url, downloader.TaskTarget(body.Target), strings.Split(body.Path, "/"), time.Now().AddDate(0, 0, body.Timeout).Sub(time.Now()))
	if nil != err {
		return response.Unknown, nil, err
	}

	var res = StartResponse{}
	res.Id = task.Id
	res.StartTime = task.StartTime.Unix()
	res.Filename = task.Filename
	res.FileSize = task.FileSize

	return response.Ok, res, nil
}
